# -*- coding: utf-8 -*-

"""
Module implementing MyMainWindow.
"""
import sys
from PyQt5.QtWidgets import QMainWindow
from Ui_matplotPyqt5 import Ui_MainWindow  # 生成的这个前面的.   要去掉

# 自己加的
from PyQt5 import QtCore, QtWidgets
# 导入matplotlib模块并使用Qt5Agg
import matplotlib

matplotlib.use('Qt5Agg')
# 使用 matplotlib中的FigureCanvas (在使用 Qt5 Backends中 FigureCanvas继承自QtWidgets.QWidget)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import numpy as np
from numpy import *
from matplotlib.figure import Figure

# 为了显示中文
# 如果是在 PyCharm 里，只要下面一行，上面的一行可以删除
plt.rcParams['font.sans-serif'] = ['SimHei']
# 用来正常显示负号
plt.rcParams['axes.unicode_minus'] = False


class MyMainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """

    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)

        layout = QtWidgets.QVBoxLayout(self.graphicsView)
        # matplotlib画布控件和普通PyQt的用法一样
        # 创建 matplotlib画布控件
        sc = MyStaticMplCanvas(self.graphicsView, width=5, height=4, dpi=100)
        dc = MyDynamicMplCanvas(self.graphicsView, width=5, height=4, dpi=100)
        # 添加到布局
        layout.addWidget(sc)
        layout.addWidget(dc)
        self.graphicsView.setFocus()  # 得到焦点
        self.setCentralWidget(self.graphicsView)
        self.statusBar().showMessage("All hail matplotlib!", 2000)

        # 点击下拉菜单action
        self.actionShop.triggered.connect(self.gotoShopUrl)

    def gotoShopUrl(self):
        import webbrowser
        webbrowser.open("https://ilovemcu.taobao.com")


# 画布控件继承自 matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg 类
class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)  # 调用基类的初始化函数
        self.setParent(parent)

        # 尺寸缩放策略
        FigureCanvas.setSizePolicy(self,
                                   QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass  # 再次被继承时被同名方法覆盖，所有这里可为pass


# 再继承第一个自定义画布控件类
class MyStaticMplCanvas(MyMplCanvas):  # 静态画布类
    """Simple canvas with a sine plot."""

    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s,)
        self.axes.set_title('静态图y=sin(x)')
        self.axes.set_xlabel('x轴')
        self.axes.set_ylabel('x轴')


# 再继承第一个自定义画布控件类
class MyDynamicMplCanvas(MyMplCanvas):  # 动态态画布类
    """A canvas that updates itself every second with a new plot."""

    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.update_figure)
        timer.start(1000)  # 每1000秒发射timeout信号，更新图形

    def compute_initial_figure(self):
        self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')
        self.axes.set_title('动态图')
        self.axes.set_xlabel('x轴')
        self.axes.set_ylabel('x轴')

    def update_figure(self):
        # Build a list of 4 random integers between 0 and 10 (both inclusive)
        l = [random.randint(0, 10) for i in range(4)]
        self.axes.cla()  # 清除已绘的图形
        self.axes.plot([0, 1, 2, 3], l, 'r')
        self.axes.set_title('动态图')
        self.axes.set_xlabel('x轴')
        self.axes.set_ylabel('x轴')
        self.draw()  # 重新绘制


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myshow = MyMainWindow()
    myshow.show()
    sys.exit(app.exec_())
